package com.situ.springbootscientific.interceptor;

import com.situ.springbootscientific.pojo.Auth;
import com.situ.springbootscientific.pojo.Researchers;
import com.situ.springbootscientific.pojo.query.AuthQuery;
import com.situ.springbootscientific.service.IAuthService;
import com.situ.springbootscientific.service.IResearchersService;
import com.situ.springbootscientific.service.impl.AuthServiceImpl;
import com.situ.springbootscientific.utils.CookieUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    IAuthService authService;
    @Autowired
    IResearchersService researchersService;
    @Autowired
    public LoginInterceptor(IResearchersService researchersService, IAuthService authService) {
        this.researchersService = researchersService;
        this.authService = authService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断用户有没有登录
        //2.如果登录了，就放行，可以访问后台的资源
        //3.如果没有登录，跳转到登录界面
        HttpSession session = request.getSession();
        Researchers researchers = (Researchers) session.getAttribute("researchers");
        //System.out.println("哒哒"+researchers);
        /*if (researchers == null) {
            System.out.println("null??");
            //没有登录，跳转到登录界面
            response.sendRedirect("/page/login");
            return false;
        }*/
        if (researchers == null) {
            Cookie cookie = CookieUtil.getCookie(request, "autoLogin");
            System.out.println("cookie"+cookie.getValue());
            if (cookie != null) {
                String[] values = cookie.getValue().split("&");
                String name = values[0];
                String password = values[1];
                researchers = researchersService.login(name, password);
                if (researchers != null) {
                    session.setAttribute("researchers", researchers);
                    List<Auth> authList = authService.selectByRole(researchers.getRole());
                    session.setAttribute("authList", authList);
                } else {
                    response.sendRedirect("/page/login");
                    return false;
                }
            } else {
                response.sendRedirect("/page/login");
                return false;
            }
        }

        //已经登录，放行
        return true;
    }
}
